﻿@{
    ViewData["Title"] = "邮件模板";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


<h1>@ViewData["Title"]</h1>

<div id="pageContainer">
    <el-row>
        <el-form :inline="true"   size="small">
            <el-form-item label="模板名称">
                <el-input v-model="filterparam.subject" placeholder="请输入模板名称"></el-input>
            </el-form-item>
            <el-form-item label="是否启用">
                <el-select v-model="filterparam.status" placeholder="是否启用">
                    <el-option label="全部" value=""></el-option>
                    <el-option label="启用" value="true"></el-option>
                    <el-option label="禁用" value="false"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary"  icon="el-icon-search"  @@click="search">搜索</el-button>

                <el-button type="primary"  icon="el-icon-circle-plus-outline" @@click="add(true)">新增</el-button>

                <el-button type="primary" @@click="clearData">清理筛选</el-button>
                <strong><a href="/home/index">如何使用：</a> </strong>参照对应的功能描述
            </el-form-item>
        </el-form>


       

    </el-row>
    <el-row>
      
        
    </el-row>

    <!--设置Table-->
    <el-row v-loading="loading">
        <el-table :data="tableData" border height="760" stripe>
            <el-table-column prop="id" label="模板编号" width="100"></el-table-column>
            <el-table-column prop="name" label="模板名称"></el-table-column>

            <el-table-column prop="subject" label="邮件主题"></el-table-column>
            <el-table-column prop="sqLparams" label="Sql参数">
                <template slot-scope="scope">
                    <span size="medium" class="el-tag el-tag--small el-tag--info" v-for="item in scope.row.sqlParams">
                        {{ item }}
                    </span>
                </template>
            </el-table-column>

            <el-table-column label="数据表现形式" width="100">
                <template slot-scope="scope">
                    {{scope.row.dataAttachmentType == '1'?"附件":"内嵌HTML"}}
                </template>

            </el-table-column>

            <el-table-column prop="multipleSheet" label="多个结果" width="50">
                <template slot-scope="scope">
                    {{ scope.row.multipleSheet?"是":"否"}}
                </template>
            </el-table-column>
            <el-table-column prop="sheetNames" label="多表名称">
                <template slot-scope="scope">

                    <span size="medium" class="el-tag el-tag--small el-tag--info" v-for="item in scope.row.sheetNames">
                        {{ item }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间">
                @*<template slot-scope="scope">
                        {{ kede.dateformat(new Date(scope.row.updateTime),"yyyy-MM-dd hh:mm:ss")}}
                    </template>*@
            </el-table-column>
            <el-table-column prop="isEnable" label="状态" align="center" width="80">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.isEnable == '0' ? 'primary' : 'success'" disable-transitions>{{scope.row.isEnable == '1'?"启用":"未启用"}}</el-tag>
                </template>


            </el-table-column>

            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <i class="el-icon-edit icon-medium cl-link pointer" title="编辑" @@click="update(scope.row,true)"></i>
                    <a :href="'/etlogs/'+scope.row.id"><i class="el-icon-tickets  icon-medium cl-link pointer" title="查看执行日志"></i></a>

                    <i class="el-icon-setting icon-medium cl-link pointer" title="如何调用该任务" @@click="opentip(scope.row)"></i>
                    <i class="el-icon-caret-right icon-medium cl-link pointer" title="发送测试" @@click="opensend(scope.row)"></i>
                </template>

            </el-table-column>
        </el-table>
    </el-row>

    <el-row>
        <el-pagination v-if="page.totalCount>0" background :page-size="page.pageSize"
                       :pager-count="15"
                       :current-page.sync="page.pageIndex"
                       @@current-change="queryData"
                       layout="prev, pager, next,total"
                       :total="page.totalCount">
        </el-pagination>
    </el-row>


</div>




<div>

    <template id="testComponent">
        <div>
            <el-tag :key="tag" v-for="tag in dynamictags" closable @@close="handleClose(tag)">
                {{tag}}
            </el-tag>
            <el-input class="input-new-tag" v-if="inputvisible" v-model="inputvalue" ref="saveTagInput" size="small" @@keyup.enter.native="handleInputConfirm" @@blur="handleInputConfirm">
            </el-input>
            <el-button v-else class="button-new-tag" size="small" @@click="showInput">+ 新增</el-button>


        </div>
    </template>
    <script>

        Vue.component('tag-list', {
            // props: ['dynamictags', 'inputvisible', 'inputvalue'],
            props: {
                dynamictags: Array,
            },
            data: function () {
                return {
                    inputvisible: false,
                    inputvalue: ''
                };
            },
            methods: {
                handleClose(tag) {
                    this.dynamictags.splice(this.dynamictags.indexOf(tag), 1);
                },

                showInput() {
                    //this.$emit("update:inputvisible",true);
                    this.inputvisible = true;
                    this.$nextTick(_ => {
                        this.$refs.saveTagInput.$refs.input.focus();
                    });
                },

                handleInputConfirm() {
                    let inputvalue = this.inputvalue;
                    let _isok = !_.includes(this.dynamictags, inputvalue);
                    if (inputvalue && _isok) {
                        this.dynamictags.push(inputvalue);
                    }
                    this.inputvisible = false;
                    this.inputvalue = '';
                }
            },
            template: '#testComponent'
        });


    </script>
</div>





<div id="editTemplate">
    <el-row>
        <!--弹出框  邮件模板-->
        <el-dialog :visible.sync="isEditEmailTemplate" width="50%">

            <div slot="title">
                <span class="el-dialog__title"> {{title}}邮件模板</span>   <i class="cl-info"></i>
                <el-row style=" border-bottom: 1px solid #ebebeb;"></el-row>
            </div>
            <el-form label-width="120px">
                <el-form-item label="模板名称">
                    <el-input size="small" v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="SMTP">
                    @*<el-input size="small" v-model="form.mailSenderId"></el-input>*@
                    <el-select size="small" v-model="form.mailSenderId" filterable placeholder="请选择用哪个SMTP服务发送">
                        <el-option v-for="item in smtpArray"
                                   :key="item.key"
                                   :label="item.value"
                                   :value="item.key">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="发送者昵称">
                    <el-input size="small" v-model="form.sendName"></el-input>
                </el-form-item>
                <el-form-item label="发送地址">
                    <tag-list :dynamictags="form.recipients"></tag-list>
                </el-form-item>
                <el-form-item label="抄送地址">
                    <tag-list :dynamictags="form.cc"></tag-list>
                </el-form-item>
                <el-form-item label="密送地址">
                    <tag-list :dynamictags="form.bcc"></tag-list>
                </el-form-item>
                <el-form-item label="邮件主题">
                    <el-input size="small" v-model="form.subject"></el-input>
                </el-form-item>
                <el-form-item label="模板内容">
                    <div style="width:95%;height:160px;">
                        <section id="myEditor" v-html="form.body">
                        </section>
                    </div>
                </el-form-item>

                <el-form-item label=""><strong>内嵌提示：</strong> 如果数据内嵌到HTML，请在内容中输入占位符 格式（#表名称1#  #表名称2#），应与表名称保持一致</el-form-item>
                <el-form-item label="数据附加类型">

                    <el-radio-group v-model="form.dataAttachmentType">
                        <el-radio :label="0">内嵌Htm</el-radio>
                        <el-radio :label="1">xlsx附件</el-radio>

                    </el-radio-group>

                </el-form-item>
                <el-form-item label="多个结果输出">

                    <el-switch v-model="form.multipleSheet" active-text="是" inactive-text="否"></el-switch>
                </el-form-item>

                <el-form-item v-show="form.multipleSheet" label="结果名称">
                    <tag-list :dynamictags="form.sheetNames"></tag-list>

                </el-form-item>
                <el-form-item label="数据库执行实例">
                    <el-select size="small" v-model="form.execInstance" filterable placeholder="请选择在哪个数据库上执行">
                        <el-option v-for="item in sqlArray"
                                   :key="item.key"
                                   :label="item.value"
                                   :value="item.key">
                        </el-option>
                    </el-select>

                </el-form-item>
                <el-form-item label="参数提示">执行脚本里的参数个占位符，该参数的具体值由执行时传入并替换SQL脚本的内容</el-form-item>
                <el-form-item label="数据参数" title="用来做脚本内容的替换">
                    <tag-list :dynamictags="form.sqlParams"></tag-list>

                </el-form-item>
                <el-form-item label="SQL脚本">
                    @*<div id="form.sqlScript"></div>*@

                    <div style="width:95%;">
                        <textarea id="CodeEditor">{{form.sqlScript}}</textarea>
                    </div>

                </el-form-item>


                <el-form-item label="状态">

                    <el-switch v-model="form.isEnable" active-text="启用" inactive-text="禁用"></el-switch>
                </el-form-item>

            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-row style=" border-bottom: 1px solid #ebebeb;"></el-row>
                <el-button size="small" round @@click="saveChange" v-if="canUpdate">确定</el-button>
                <el-button size="small" round @@click="isEditEmailTemplate=false">关闭</el-button>
            </div>


        </el-dialog>
        <!--弹出框end-->
    </el-row>

</div>
<div id="editEmailParams">
    <el-row>
        <!--弹出框  邮件模板-->
        <el-dialog :visible.sync="isShow" width="50%">

            <div slot="title">
                <span class="el-dialog__title"> 输入参数</span>   <i class="cl-info"></i>
                <el-row style=" border-bottom: 1px solid #ebebeb;"></el-row>
            </div>
            <el-form label-width="120px">
                <el-form-item label="模板名称">
                    {{form.name}}
                </el-form-item>



                <el-form-item :label="item.Key" :key="item.Key" v-for="item in form.eParams">
                    <el-input size="small" v-model="item.Value"></el-input>
                </el-form-item>

            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-row style=" border-bottom: 1px solid #ebebeb;"></el-row>
                <el-button size="small" round @@click="send">开始测试</el-button>
                <el-button size="small" round @@click="isShow=false">关闭</el-button>
            </div>


        </el-dialog>
        <!--弹出框end-->
    </el-row>

</div>

<div id="emailTips">
    <el-row>
        <!--弹出框  邮件模板-->
        <el-dialog :visible.sync="isShow" width="50%">

            <div slot="title">
                <span class="el-dialog__title"> 如何该任务部署脚本</span>   <i class="cl-info"></i>
                <el-row style=" border-bottom: 1px solid #ebebeb;"></el-row>
            </div>
            <el-row>
                <strong>邮件模板</strong> :{{form.name}}<br /><br />
                <strong>1.直接运行程序 （windows linux Mac通用）</strong><br />

                命令行:
                <el-alert :title="runcommond" type="info" :closable="false"></el-alert>
                带日志的命令行:
                <el-alert :title="runcommondlog" type="info" :closable="false"></el-alert>


            </el-row>
            <el-row>
                <strong>2.在linux上定时调度</strong><br />
                使用corntab 调度(直接把该语句复制到crontab，即完成部署):
                <el-alert :title="runcommondCronlog" type="info" :closable="false"></el-alert>

            </el-row>
            <el-row>

                提示:<br />
                1.  xxxxx 为自定义填充的值<br />
                <pre><code>
    crontab语法结构：
    # 每月的最后1天
    0 0 L * * *

    说明：
    Linux
    *    *    *    *    *
    -    -    -    -    -
    |    |    |    |    |
    |    |    |    |    +----- day of week (0 - 7) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
    |    |    |    +---------- month (1 - 12) OR jan,feb,mar,apr ...
    |    |    +--------------- day of month (1 - 31)
    |    +-------------------- hour (0 - 23)
    +------------------------- minute (0 - 59)
</code></pre>

            </el-row>
            <div slot="footer" class="dialog-footer">
                <el-row style=" border-bottom: 1px solid #ebebeb;"></el-row>
                <el-button size="small" round @@click="isShow=false">关闭</el-button>
            </div>
        </el-dialog>
        <!--弹出框end-->
    </el-row>

</div>


@section styles{
    <link href="~/js/codemirror/lib/codemirror.css" rel="stylesheet" />
    <link href="~/js/codemirror/addon/fold/foldgutter.css" rel="stylesheet" />
    <link href="~/js/codemirror/addon/hint/show-hint.css" rel="stylesheet" />
    <link href="~/js/codemirror/theme/neat.css" rel="stylesheet" />
    <link href="~/js/froala-editor/froala_editor.pkgd.css" rel="stylesheet" />
    <style type="text/css">

        a[href="https://froala.com/wysiwyg-editor"], a[href="https://www.froala.com/wysiwyg-editor?k=u"] {
            display: none !important;
            position: absolute;
            top: -99999999px;
        }

        .el-tag + .el-tag {
            margin-left: 10px;
        }

        .button-new-tag {
            margin-left: 10px;
            height: 32px;
            line-height: 30px;
            padding-top: 0;
            padding-bottom: 0;
        }

        .input-new-tag {
            width: 90px;
            margin-left: 10px;
            vertical-align: bottom;
        }
    </style>
}
@section scripts{

    <script src="~/js/codemirror/lib/codemirror.js"></script>
    <script src="~/js/codemirror/mode/sql/sql.js"></script>
    <script src="~/js/codemirror/addon/hint/sql-hint.js"></script>
    <script src="~/js/codemirror/addon/fold/foldgutter.js"></script>
    <script src="~/js/froala-editor/froala_editor.pkgd.min.js"></script>
    <script src="~/js/froala-editor/languages/zh_cn.js"></script>
    <script src="~/api/data/getTestdata" type="text/javascript"></script>
    <script src="~/api/data/GetMetaDataSQlInstanceAll" type="text/javascript"></script>
    <script src="~/api/data/GetMetaDataMailSender" type="text/javascript"></script>

    <script>
        pagInit = {
            theEdit: null,
            theCodeMirror: null,
            initEdit: function (eleid, centent) {
                let myele = document.getElementById(eleid);
                this.theEdit = new FroalaEditor(myele, {
                    toolbarButtons: [
                        ['bold', 'italic', 'underline', 'paragraphFormat', 'formatOL', 'formatUL'],
                        ['insertHTML', 'undo', 'redo', 'html']
                    ],
                    placeholder: "请填写内容",
                    language: "zh_cn",//国际化
                    quickInsertButtons: ['table', 'ul', 'ol', 'hr'],//快速插入项
                });

            },
            initTextArea: function (eleid, centent) {
                let myele = document.getElementById(eleid);

               // { key:1, value:"Postgres"}, { key:2, value:"SqlServer"}
                let _si = _.filter(dr_sqlinstance, { key: editData.form.execInstance });
                var sqltype = 1;
                if (_si.length>0) {
                    sqltype = _si[0].DbType;
                }
                var sqldmode = sqltype == 1 ? "text/x-pgsql" : "text/x-mssql";
                this.theCodeMirror = CodeMirror.fromTextArea(myele, {
                    lineNumbers: true,
                    matchBrackets: true,
                    styleActiveLine: true,
                    theme: "neat",
                    mode: sqldmode,
                    readOnly: false,
                    showCursorWhenSelecting: true,
                });
                this.theCodeMirror.setSize("auto", "300px");
                if (centent != null)
                    pagInit.theCodeMirror.setValue(centent);
            },
            sqlArray: dr_sqlinstance,
            smtpArray: dr_mailSender
        };

        var editData = new Vue({
            el: "#editTemplate",
            data: {
                isEditEmailTemplate: false,
                title: "编辑",
                editeleId: "#myEditor",
                canUpdate: true,
                theEdit: null,
                myCodeMirror: null,
                initTag: true,
                sqlArray: pagInit.sqlArray,
                smtpArray: pagInit.smtpArray,
                form: {
                    bcc: [],
                    body: "",
                    cc: [],
                    dataAttachmentType: 1,
                    execInstance: 0,
                    id: 0,
                    isEnable: false,
                    mailSenderId: 0,
                    multipleSheet: false,
                    name: "",
                    recipients: [],
                    sendName: "",
                    sheetNames: [],
                    sqlParams: [],
                    sqlScript: "",
                    subject: "",
                    updatetime: ""
                }
            },
            watch: {
                isEditEmailTemplate: function (val) {

                    if (val) {
                        setTimeout(function () {
                            pagInit.initEdit("myEditor");
                            pagInit.initTextArea("CodeEditor", editData.form.sqlScript);
                        }, 200);
                    } else {
                        pagInit.theEdit.destroy();
                        pagInit.theCodeMirror.toTextArea();
                    }
                }

            },
            mounted() {

            },
            methods: {
                reset: function () {
                    this.form.bcc = [];
                    this.form.body = "";
                    this.form.cc = [];
                    this.form.dataAttachmentType = 1;
                    this.form.execInstance = 0;
                    this.form.id = 0;
                    this.form.isEnable = false;
                    this.form.mailSenderId = 0;
                    this.form.multipleSheet = false;
                    this.form.name = "";
                    this.form.recipients = [];
                    this.form.sendName = "";
                    this.form.sheetNames = [];
                    this.form.sqlParams = [];
                    this.form.sqlScript = "";
                    this.form.subject = "";
                    this.form.updatetime = new Date();
                },
                print: function (centent) {
                    console.log("数据测试:" + centent + "  Time:" + new Date());
                },
                saveChange: function () {

                    var _sqlscript = pagInit.theCodeMirror.getValue();
                    var _etBody = pagInit.theEdit.html.get();
                   _etBody= _etBody.replace('<p data-f-id="pbf" style="text-align: center; font-size: 14px; margin-top: 30px; opacity: 0.65; font-family: sans-serif;">Powered by <a href="https://www.froala.com/wysiwyg-editor?pb=1" title="Froala Editor">Froala Editor</a></p>','')
                    let data = JSON.parse(JSON.stringify(this.form));
                    data.body = _etBody;
                    data.sqlScript = _sqlscript;
                    axios.post("/api/Data/UpdateEmailTemplates", data).then(function (result) {
                        if (result.data.isSuccess) {
                            pageVue.Tips("更新完成");
                            editData.isEditEmailTemplate = false;
                            setTimeout(function () {
                                
                                pageVue.search();
                            }, 500);

                        }


                    });
                    console.log("修改数据  ");




                }
            }

        });


        var pageVue = new Vue({
            el: '#pageContainer',
            data: {
                loading: false,
                filterparam: {
                    subject: '',
                    status: "",
                },
                dateRange: ["", ""],
                tableData: [],
                page: { pageIndex: 1, pageSize: 20, totalCount: 0 }


            },
            methods: {
                /*搜索数据*/
                search: function () {
                
                    this.queryData();

                },
                clearData: function () {
                    this.filterparam.subject = "";
                    this.filterparam.status = "";
                  
                },
                queryData: function () {
                    let query = JSON.parse(JSON.stringify(this.filterparam));
                    query.pageindex = this.page.pageIndex;
                    query.pagesize = this.page.pageSize;
                    this.loading = true;
                    kede.get("/api/Data/FindEmailTemplates", query, function (result) {
                        pageVue.loading = false;
                        pageVue.filltable(result);

                    }, "json");

                },
                filltable: function (result) {
                    this.tableData = result.data.lists;
                    this.page.totalCount = result.data.page.totalCount;
                },
                Tips: function (centent, type) {
                    type = type || "info";
                    this.$message({
                        message: centent,
                        type: type
                    });
                },
                array2Str(_arrys, _separats) {
                    let _data = _arrys || [];
                    return _data.join(_separats);
                },
                update: function (data, _canUpdate) {
                    editData.title = "编辑";
                    editData.form = JSON.parse(JSON.stringify(data));
                    editData.isEditEmailTemplate = true;

                },
                opensend:function (data) {
                    //填写入参
                    //请求后台数据
                     editParamsVue.form.name = data.name;
                    editParamsVue.form.etId = data.id;
                    editParamsVue.form.eParams =_.map( data.sqlParams, function(v){return {Key:v,Value:''};});
                    editParamsVue.isShow = true;
                },
                opentip: function (data) {
                    emailTipsVue.form = data;
                    emailTipsVue.isShow = true;
                },
                preview: function (id) {
                     @*v-bind:href="~/logs/{scope.row.id}/*@
                    window.location.href = "/logs/"+id;
                },
                add: function () {
                    editData.reset();
                    editData.title = "新增";
                    editData.isEditEmailTemplate = true;
                }
            }
        });
        pageVue.search();


        var editParamsVue = new Vue({
            el: '#editEmailParams',
            data: {
                isShow: false,
                form: {
                    name:'',
                    etId: 0,
                    eParams: [],
                }


            },
            methods: {
                send: function () {
                    //填写入参
                    //请求后台数据
                    var data = {};
                    data.etId = this.form.etId;
                    data.eParams = this.form.eParams;
                    console.log(JSON.stringify(data));
                    axios.post("/api/Data/ExecEmailTest", data).then(function (result) {
                        if (result.data.isSuccess) {
                            pageVue.Tips("发送完成");
                        }
                    });
                    console.log("修改数据  ");




                }

            }
        });
        var emailTipsVue = new Vue({
            el: '#emailTips',
            @*execPath:"@ViewBag.ExecPath",*@

            data: {
                execPath:"@(ViewBag.ExecPath)",
                isShow: false,
                form: {}
            }, computed: {
                runcommond: function () {
                   return this.getbaseCommond(false);

                },
                runcommondlog: function () {
                    return this.getbaseCommond(true);
                },
                runcommondCronlog: function () {
                    let _value = [];
                    _value.push("* * * * * bash ");
                    _value.push(this.getbaseCommond(true));
                    return _value.join("");
                },

            },
            methods: {
                getbaseCommond: function (islog) {
                    let _val = [];
                    _val.push("dotnet ");
                    _val.push(this.execPath + "/ARS.Service.dll ");
                    //填充参数

                   let eParams = _.map(this.form.sqlParams, function (v) { return v + '=xxxxx'; });
                    eParams.push("etId=" + this.form.id);
                    _val.push(eParams.join(" "));
                    if (islog) {
                        _val.push(">>");
                        _val.push(this.execPath + "/logs/" + this.form.id + "/" + this.form.subject + "_$(date +%Y-%m-%d_%H:%M).log");

                    }
                    return _val.join("");
            //          var _execdll = $"{Program.appSetting.ExecPath}/ARS.Service.dll";
            //var _logpath = $"{Program.appSetting.ExecPath}/logs/{model.etId}/{DateTime.Now:yyyyMMdd_hh_mm_ss}.log";

                }
            }
        });



    </script>
}








